package com.jn.zhinongbao.adapter;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;
import com.google.android.material.textfield.TextInputEditText;

public class LoginActivity extends AppCompatActivity {

    private TextInputEditText etUsername, etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private DatabaseHelper databaseHelper;
    private PreferenceManager preferenceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initViews();
        initDatabase();
        setupClickListeners();
        
        // 检查是否是从退出登录跳转过来的
        checkIfLoggedOut();
        
        // 检查是否已登录
        checkLoginStatus();
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        tvRegister = findViewById(R.id.tv_register);
    }

    private void initDatabase() {
        databaseHelper = new DatabaseHelper(this);
        preferenceManager = new PreferenceManager(this);
    }

    private void setupClickListeners() {
        btnLogin.setOnClickListener(v -> performLogin());
        tvRegister.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    private void checkLoginStatus() {
        // 创建测试商家账户（仅在调试时使用）
        createTestMerchantIfNeeded();
        
        if (preferenceManager.isLoggedIn()) {
            // 已登录，根据用户角色跳转到相应界面
            int userRole = preferenceManager.getCurrentUserRole();
            Intent intent;
            if (userRole == 0) { // 商家
                intent = new Intent(LoginActivity.this, MerchantActivity.class);
            } else { // 普通用户
                intent = new Intent(LoginActivity.this, MainActivity.class);
            }
            startActivity(intent);
            finish();
        }
    }

    /**
     * 创建测试商家账户（仅用于调试）
     */
    private void createTestMerchantIfNeeded() {
        // 检查是否存在测试商家
        if (!databaseHelper.isUsernameExists("testmerchant")) {
            User testMerchant = new User("testmerchant", "123456", "13800000000", 0, "测试农场");
            boolean result = databaseHelper.registerUser(testMerchant);
            if (result) {
                // 创建测试数据
                createTestData();
                Toast.makeText(this, "已创建测试商家账户: testmerchant/123456", Toast.LENGTH_LONG).show();
            }
        }
        
        // 检查是否存在测试用户
        if (!databaseHelper.isUsernameExists("testuser")) {
            User testUser = new User("testuser", "123456", "13900000000", 1, null);
            boolean result = databaseHelper.registerUser(testUser);
            if (result) {
                Toast.makeText(this, "已创建测试用户账户: testuser/123456", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 创建测试数据（仅用于调试）
     */
    private void createTestData() {
        // 创建测试商品数据
        databaseHelper.createTestProductsWithImages();
        // 创建测试购物车和订单数据
        databaseHelper.createTestCartAndOrderData();
    }

    /**
     * 检查是否是从退出登录跳转过来的
     */
    private void checkIfLoggedOut() {
        Intent intent = getIntent();
        if (intent != null && intent.getBooleanExtra("fromLogout", false)) {
            String message = intent.getStringExtra("logoutMessage");
            if (message != null) {
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void performLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 输入验证
        if (TextUtils.isEmpty(username)) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            etPassword.setError("请输入密码");
            etPassword.requestFocus();
            return;
        }

        // 尝试登录
        User user = databaseHelper.loginUser(username, password);
        if (user != null) {
            // 登录成功
            preferenceManager.saveUserLogin(user.getId(), user.getUsername(), user.getRole());
            
            // 调试信息：显示保存的用户信息
            String debugInfo = String.format("用户ID: %d, 用户名: %s, 角色: %d, 店铺: %s", 
                    user.getId(), user.getUsername(), user.getRole(), 
                    user.getShopName() != null ? user.getShopName() : "无");
            Toast.makeText(this, "登录成功！" + debugInfo, Toast.LENGTH_LONG).show();
            
            // 根据用户角色跳转到相应界面
            Intent intent;
            if (user.getRole() == 0) { // 商家
                intent = new Intent(LoginActivity.this, MerchantActivity.class);
            } else { // 普通用户
                intent = new Intent(LoginActivity.this, MainActivity.class);
            }
            startActivity(intent);
            finish();
        } else {
            // 登录失败
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 处理返回键，显示退出应用确认
     */
    @SuppressLint("MissingSuperCall")
    @Override
    public void onBackPressed() {
        showExitAppDialog();
    }

    /**
     * 显示退出应用确认对话框
     */
    private void showExitAppDialog() {
        new android.app.AlertDialog.Builder(this)
                .setTitle("退出应用")
                .setMessage("确定要退出农业宝藏应用吗？")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("确定", (dialog, which) -> {
                    finishAffinity();
                    System.exit(0);
                })
                .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                .setCancelable(true)
                .show();
    }
} 